package com.yq.ylmall.order.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yq.ylmall.common.utils.JwtUtils;
import com.yq.ylmall.dto.order.OrderInfoDto;
import com.yq.ylmall.dto.order.PaymentInfoDto;
import com.yq.ylmall.enums.payment.OrderStatus;
import com.yq.ylmall.model.order.OrderInfo;
import com.yq.ylmall.model.payment.PaymentInfo;
import com.yq.ylmall.order.service.IOrderInfoService;
import com.yq.ylmall.result.Result;
import com.yq.ylmall.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "orderApi接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/order")
@Slf4j
public class OrderApiController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @GetMapping("/update/orderStatus/{orderNo}/{status}")
    public void updateOrderStatus(@PathVariable("orderNo") String orderNo, @PathVariable("status") Integer status) {
        log.info("updateOrderStatus orderNo:{},status:{}", orderNo, status);
        orderInfoService.update(Wrappers.<OrderInfo>lambdaUpdate().set(OrderInfo::getOrderStatus, status).eq(OrderInfo::getOrderNo, orderNo));
    }

    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody OrderInfoDto orderInfoDto, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = JwtUtils.verifyAdminTokenAndGetId(token);
        orderInfoDto.setUserId(userId.longValue());
        return orderInfoService.createOrder(orderInfoDto);
    }


    @PostMapping("/getOrderInfoByOrderNo/{orderNo}")
    public OrderInfo getOrderInfoByOrderNo(@PathVariable String orderNo) {
        OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper<OrderInfo>().eq("order_no", orderNo));
        if(orderInfo == null) {
            return null;
        }
        return orderInfo;
    }

    @PostMapping("/update/paymentInfo")
    public void updatePaymentInfo(@RequestBody PaymentInfoDto paymentInfo) {
        log.info("updatePaymentInfo orderInfo:{}", paymentInfo);
    }

    @GetMapping("/query/orderStatus/{orderNo}")
    public Result queryOrderStatus(@PathVariable String orderNo) {
        OrderInfo orderInfo = orderInfoService.getOne(new QueryWrapper<OrderInfo>().eq("order_no", orderNo));
        if(OrderStatus.SUCCESS.getStatus() == orderInfo.getOrderStatus()) {
            return Result.ok(ResultCode.SUCCESS);
        }
        return Result.ok(ResultCode.OPERATE_SUCCESS);
    }

}
